import java.util.Arrays;

public class TestHeap {
    private int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent, usedSize);
        }
    }

    public void shiftDown(int parent, int len) {
        int child = parent * 2 + 1;
        while (child < len) {
            if (child + 1 < len && elem[child + 1] > elem[child]) {
                child++;
            }
            if (elem[parent] < elem[child]) {
                swap(parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    public int pop() {
        if(isEmpty()) {
            return -1;
        }
        int oldVal = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize-1);
        return oldVal;
    }



    public void shiftUp(int child) {
        int parent = (child-1)/2;
        while(parent>=0) {
            if(elem[parent]<elem[child]) {
                swap(parent,child);
                child = parent;
                parent = (child-1)/2;
            }else{
                break;
            }
        }
    }

    public void swap(int a, int b) {
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public int getTop() {
        return elem[0];
    }

    public void print() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
}
